// src/contexts/UserContext.tsx
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import api from '@/services/api';
import { UserInfo } from '@/types';

interface UserContextType {
  user: UserInfo | null;
  token: string | null;
  login: (phone: string, password: string, rememberMe?: boolean) => Promise<boolean>;
  logout: () => Promise<void>;
  isLoading: boolean;
}

const UserContext = createContext<UserContextType | undefined>(undefined);

export const UserProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [user, setUser] = useState<UserInfo | null>(null);
  const [token, setToken] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(true);

  // 初始化时检查本地存储中的用户信息
  useEffect(() => {
    const storedToken = localStorage.getItem('token');
    const storedUserInfo = localStorage.getItem('userInfo');
    
    if (storedToken && storedUserInfo) {
      setToken(storedToken);
      try {
        setUser(JSON.parse(storedUserInfo));
      } catch (e) {
        console.error('Failed to parse user info from localStorage', e);
      }
    }
    setIsLoading(false);
  }, []);

  const login = async (phone: string, password: string, rememberMe: boolean = false): Promise<boolean> => {
    setIsLoading(true);
    try {
      const response = await api.login({
        phone,
        password,
        clientId: "",
        grantType: "",
        userType: ""
      });

      // 根据控制台日志，response直接是data对象，而不是{code, message, data}格式
      console.log("UserContext login response:", response);
      
      // 检查response是否有token字段来判断是否登录成功
      if (response && (response as any).token) {
        // 登录成功
        const token = (response as any).token;
        const userInfo = (response as any).userInfo;
        
        // 保存到状态
        setToken(token);
        setUser(userInfo);
        
        // 保存到本地存储
        localStorage.setItem('token', token);
        localStorage.setItem('userInfo', JSON.stringify(userInfo));
        
        // 如果选择了"记住我"，保存用户信息
        if (rememberMe) {
          localStorage.setItem('savedPhone', phone);
          localStorage.setItem('rememberMe', 'true');
        }
        
        console.log("UserContext login successful");
        return true;
      } else {
        // 登录失败
        console.log("UserContext login failed");
        throw new Error('登录失败');
      }
    } catch (error) {
      console.error('Login failed:', error);
      throw error;
    } finally {
      setIsLoading(false);
    }
  };

  const logout = async (): Promise<void> => {
    setIsLoading(true);
    try {
      // 调用登出API
      await api.logout();
    } catch (error) {
      console.error('Logout API call failed:', error);
    } finally {
      // 清除状态和本地存储
      setToken(null);
      setUser(null);
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      // 注意：我们不清除"记住我"的相关信息，这样用户下次访问时仍然可以显示手机号
      setIsLoading(false);
    }
  };

  return (
    <UserContext.Provider value={{ user, token, login, logout, isLoading }}>
      {children}
    </UserContext.Provider>
  );
};

export const useUser = (): UserContextType => {
  const context = useContext(UserContext);
  if (context === undefined) {
    throw new Error('useUser must be used within a UserProvider');
  }
  return context;
};